package com.newland.starpos.partner.listen;

import com.newland.starpos.partner.bean.po.Grade;
import com.newland.starpos.partner.bean.po.GradeFlow;
import com.newland.starpos.partner.bean.po.User;
import com.newland.starpos.partner.mapper.GradeFlowMapper;
import com.newland.starpos.partner.mapper.GradeMapper;
import com.newland.starpos.partner.mapper.UserMapper;
import com.newland.starpos.partner.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * Created by liuNW on 2018/9/29.
 */
@Slf4j
@Component
public class UserRegisterListener implements ApplicationListener<UserRegisterEvent> {

    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private GradeFlowMapper gradeFlowMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(UserRegisterEvent event) {
        log.info("begin async task, Initializing user data and determining " +
                "the upgrade conditions of the superior partner");
        User newUser = event.getNewUser();
        // 插入新用户的等级记录
        Grade grade = new Grade();// 等级
        grade.setUserId(newUser.getUserId());
        grade.setCreateTime(DateUtils.now());
        gradeMapper.insert(grade);

        // TODO 初始化用户帐号数据

        // 查询新用户的指定层级内的父id
        Set<Long> parentIds = userMapper.findParentIds(newUser.getUserId());
        parentIds.parallelStream().forEach((Long pid) -> {
            Grade pgrade = gradeMapper.findGrade(pid);

            GradeFlow now = new GradeFlow(pid, "partner");
            GradeFlow last = gradeMapper.findLastGradeFlow(pid, "partner");
            now.setOldValue(last == null ? "0" : last.getNewValue());
            int newValue = userMapper.countChild(pid);
            now.setNewValue(String.valueOf(newValue));
            now.setTriggerObject(String.valueOf(newUser.getUserId()));
            now.setCreTime(DateUtils.now());


            now.setOldGrade(pgrade.getGrade());
            int newGrade = matchPartnerRule(newValue);
            now.setNewGrade(newGrade);
            gradeFlowMapper.insert(now);
            log.info("userId : {}, flow[partner] oldValue: " +
                    now.getOldValue() + " --- newValue: " + newValue, pid);
            // 判断用户有没升级
            if(newGrade == pgrade.getPartnerGrade().intValue())
                return;
            log.info(String.format("the new level of user[userId:%6d] is inconsistent with the original level,"
                    + " oldLevel: %1d >>> newLevel: %1d", pid, pgrade.getPartnerGrade(), newGrade));
            pgrade.setPartnerGrade(newGrade);
            pgrade.setUpdateTime(DateUtils.now());
            gradeMapper.updateById(pgrade);
        });
        log.info("success, user init end");
    }

    private int matchPartnerRule(int number) {
        if (number < 50)
            return 0;
        if (number >= 50 && number < 500)
            return 1;
        return 2;
    }
}
